package com.seth.myapplication.service;

import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.support.annotation.UiThread;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.seth.myapplication.bean.Rewords;
import com.seth.myapplication.bean.User;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * Created by Seth on 2017/10/31.
 */

public class NetWorkService extends Service {
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/*");
    private OkHttpClient client = new OkHttpClient();
    private Activity mActivity;
  //  private Intent intent = new Intent("com.seth.myapplication.service.RECEIVER");
    private User mUser;
    private Intent taskGetIntent;
    private int downloagImageFlag;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public NetWorkService(FragmentActivity activity){
        mActivity = activity;
    }
    public NetWorkService(Activity activity, String str){
        mActivity = activity;
        taskGetIntent = new Intent(str);
    }


    public void usrLogin(final User user){
        mUser = user;
        String data_str = TransToJasonLogin(user);
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        RequestBody requestBody = multipartBuilder.type(MultipartBuilder.FORM)
                .addFormDataPart("join",data_str).build();
        Request.Builder builder = new Request.Builder();
        Request request = builder.url("http://139.199.9.252/join/land").post(requestBody).build();

        Call call = client.newCall(request);
        call.enqueue(new loginCallback());
    }

    public void freshTask(String data_str, String url, String name){

        Log.i("okhttpRespond",data_str);
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        RequestBody requestBody = multipartBuilder.type(MultipartBuilder.FORM)
                .addFormDataPart(name,data_str).build();
        Request.Builder builder = new Request.Builder();
        Request request = builder.url(url).post(requestBody).build();


        Call call = client.newCall(request);
        call.enqueue(new FreshCallback());
    }

    public void downloadImage(String url, int flag){
        downloagImageFlag = flag;
        String path = "http://139.199.9.252/"+url;
        Log.i("okhttpRespond",path);
        Request.Builder builder = new Request.Builder();
        final Request request = builder
                .get()
                .url(path)
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                Log.i("okhttpRespond","failure");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                Log.i("okhttpRespondDownLoad","success");

                InputStream is = response.body().byteStream();
                Bitmap bitmap= BitmapFactory.decodeStream(is);
                taskGetIntent.putExtra("result", "image");
                taskGetIntent.putExtra("bitmap",bitmap);
                taskGetIntent.putExtra("userId",downloagImageFlag);
                mActivity.sendBroadcast(taskGetIntent);
            }
        });


    }

    public void updateUsr(User user){
        mUser = user;
        String data_str = TransToJsonUpdate(user);
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        RequestBody requestBody = multipartBuilder.type(MultipartBuilder.FORM)
                .addFormDataPart("edit",data_str).build();
        Request.Builder builder = new Request.Builder();
        Request request = builder.url("http://139.199.9.252/join/edit").post(requestBody).build();

        Call call = client.newCall(request);
        call.enqueue(new UpdateCallback());
    }

    public void updateFrog(int usrID,File img){
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        RequestBody requestBody = multipartBuilder.type(MultipartBuilder.FORM)
                .addFormDataPart("userid",usrID+"")
                .addFormDataPart("head",usrID+"_frog.jpg", RequestBody.create(MediaType.parse("application/octet-stream"),img)).build();

        Request.Builder builder = new Request.Builder();
        Request request = builder.url("http://139.199.9.252/join/head").post(requestBody).build();
        Call call = client.newCall(request);
        call.enqueue(new baseCallback() {
            @Override
            protected void dealRespond(final String str) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(mActivity, str, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    public void newRegist(final User user,final Context context){
        mUser = user;
        String data_str = TransToJason(user);
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        RequestBody requestBody = multipartBuilder.type(MultipartBuilder.FORM)
                .addFormDataPart("pcmation",data_str).build();
        Request.Builder builder = new Request.Builder();
        Request request = builder.url("http://139.199.9.252/join/register").post(requestBody).build();

        Call call = client.newCall(request);
        call.enqueue(new RegisterCallback());
    }

    public void AcceptTask(int userId, int rewordId){
        String data_str = "{\"BountyId\":\""+rewordId+"\",\"userId\":\""+userId+"\"}";
        Log.i("okhttpRespond",data_str);
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        RequestBody requestBody = multipartBuilder.type(MultipartBuilder.FORM)
                .addFormDataPart("UBid",data_str).build();
        Request.Builder builder = new Request.Builder();
        Request request = builder.url("http://139.199.9.252/publish/get").post(requestBody).build();

        Call call = client.newCall(request);
        call.enqueue(new AcceptCallback());
    }

    public void getUser(String userId){
        mUser = new User();
        String data_str = userId;
        Log.i("okhttpRespond",data_str);
        MultipartBuilder multipartBuilder = new MultipartBuilder();
        RequestBody requestBody = multipartBuilder.type(MultipartBuilder.FORM)
                .addFormDataPart("userId",data_str).build();
        Request.Builder builder = new Request.Builder();
        Request request = builder.url("http://139.199.9.252/pc/mation").post(requestBody).build();

        Call call = client.newCall(request);
        call.enqueue(new GetUsrCallback());
    }

    public void uploadTask(final Rewords rewords, final Context context) {

        Rewords r = rewords;
        String data_str = TransToJason(r);

        MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
        multipartBuilder.addFormDataPart("jsonObject",data_str);
        Date date = new Date();
        if(r.getTaskImg1Url()!=null){
            Log.i("okhttpRespond","加载第一张图片");
            multipartBuilder.addFormDataPart("files",date.toString()+"img1.jpg",RequestBody.create(MediaType.parse("application/octet-stream"),r.getTaskImg1Url()));
            if(r.getTaskImg2Url()!=null){
                Log.i("okhttpRespond","加载第二张图片");
                multipartBuilder.addFormDataPart("files",date.toString()+"img2.jpg",RequestBody.create(MediaType.parse("application/octet-stream"),r.getTaskImg2Url()));
                if(r.getTaskImg3Url()!=null){
                    Log.i("okhttpRespond","加载第三张图片");
                    multipartBuilder.addFormDataPart("files",date.toString()+"img3.jpg",RequestBody.create(MediaType.parse("application/octet-stream"),r.getTaskImg3Url()));
                    if(r.getTaskImg4Url()!=null){
                        Log.i("okhttpRespond","加载第四张图片");
                        multipartBuilder.addFormDataPart("files",date.toString()+"img4.jpg",RequestBody.create(MediaType.parse("application/octet-stream"),r.getTaskImg4Url()));
                    }
                }
            }
        }
        RequestBody requestBody = multipartBuilder.build();

        Request.Builder builder = new Request.Builder();
        Request request = builder.url("http://139.199.9.252/publish").post(requestBody).build();

        Call call = client.newCall(request);
        call.enqueue(new UploadCallback());
    }


    abstract class baseCallback implements Callback{

        @Override
        public void onFailure(Request request, IOException e) {
            Log.i("okhttpRespond","failure");
            //Log.i("okhttpRespond","failure");
            e.printStackTrace();

        }

        @Override
        public void onResponse(Response response) throws IOException {
            Log.i("okhttpRespond","success");
            String str = response.body().string();
            Log.i("okhttpRespond",str);
            dealRespond(str);
        }

        protected abstract void dealRespond(String str);

    }

    class GetUsrCallback extends baseCallback{
        //Intent taskIntent = new Intent("com.seth.myapplication.service.RECEIVER.TASK");
        @Override
        protected void dealRespond(String str) {

            JSONObject userinfo = null;
            JSONObject json = null;
            synchronized(NetWorkService.this){
                try {
                    json = new JSONObject(str);
                    userinfo = json.getJSONObject("data");
                    CompleteUsrInfo(mUser,userinfo);
                    Log.i("okhttpRespond",mUser.getUsrId()+"");
                    taskGetIntent.putExtra("result","userinfo");
                    taskGetIntent.putExtra("usrInfo",mUser);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if(json==null){
                    taskGetIntent.putExtra("result","failure");
                }
                mActivity.sendBroadcast(taskGetIntent);
                }
            }
        }

    class loginCallback extends baseCallback {
        public loginCallback() {
            super();
        }
        @Override
        protected void dealRespond(String str) {
            String res = null;
            JSONObject userinfo = null;
            JSONObject json = null;
            try {
                json = new JSONObject(str);
                res = json.getString("result");
                if("login success".equals(res)){
                    userinfo = json.getJSONObject("data");
                    CompleteUsrInfo(mUser,userinfo);
                    Log.i("okhttpRespond",mUser.getNickname());
                    Log.i("USER_FROG",mUser.getFrog());
                    taskGetIntent.putExtra("result", 1);
                    taskGetIntent.putExtra("usrInfo",mUser);
                }else if("wrong password".equals(res)){
                    taskGetIntent.putExtra("result", 2);
                }else if("wrong account".equals(res)){
                    taskGetIntent.putExtra("result", 3);;
                }
                mActivity.sendBroadcast(taskGetIntent);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    class RegisterCallback extends baseCallback{
        @Override
        protected void dealRespond(String str) {
            String res = null;
            JSONObject userinfo = null;
            JSONObject json = null;
            try {
                json = new JSONObject(str);
                res = json.getString("result");
                if("1".equals(res)){
                    userinfo = json.getJSONObject("data");
                    CompleteUsrInfo(mUser,userinfo);
                    taskGetIntent.putExtra("result", 4);
                    taskGetIntent.putExtra("usrInfo",mUser);
                } else if("0".equals(res)){
                    taskGetIntent.putExtra("result", 5);
                } else if("2".equals(res)){
                    taskGetIntent.putExtra("result", 6);
                }
                mActivity.sendBroadcast(taskGetIntent);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    class UpdateCallback extends baseCallback{
        @Override
        protected void dealRespond(String str) {
            String res = null;
            JSONObject json = null;
            try {
                json = new JSONObject(str);
                res = json.getString("result");
                if("update success".equals(res)){
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mActivity, "保存成功", Toast.LENGTH_SHORT).show();
                        }
                    });
                } else if("update failed".equals(res)){
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mActivity, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    class FreshCallback extends baseCallback{
        @Override
        protected void dealRespond(String str) {
            String data = null;
            String msg = null;
            JSONArray tasks = null;
            JSONObject json = null;
            try {
                json = new JSONObject(str);
                data = json.getString("data");
                Log.i("okhttpRespond2",data.toString());
                //msg = json.getString("msg");
                ArrayList<Rewords> rewords = new ArrayList<Rewords>();
                tasks = new JSONArray(data);
                Log.i("okhttpRespond3",tasks.length()+"");
                for(int i=0;i<tasks.length();i++){
                    Rewords reword = getReword((JSONObject)tasks.get(i));
                    rewords.add(reword);
                    Log.i("okhttpRespond","获取第"+ i+"个悬赏");
                }
                Log.i("okhttpRespond","获取了"+ rewords.size()+"个天数");
                taskGetIntent.putExtra("result","success");
                //taskGetIntent.putExtra("msg",msg);
                taskGetIntent.putExtra("rewords",rewords);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(data == null){
                taskGetIntent.putExtra("result","failure");
            }
            mActivity.sendBroadcast(taskGetIntent);
        }
    }

    class UploadCallback extends baseCallback{
        @Override
        protected void dealRespond(String str) {
            String res = null;
            JSONObject json = null;
            try {
                json = new JSONObject(str);
                res = json.getString("result");
                if("1".equals(res)){
                    taskGetIntent.putExtra("result","success");
                } else if("0".equals(res)){
                    taskGetIntent.putExtra("result","failure");
                }
                mActivity.sendBroadcast(taskGetIntent);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    class AcceptCallback extends baseCallback{
        Intent intent = new Intent("com.seth.myapplication.service.ACCEPT.TASK");
        @Override
        protected void dealRespond(String str) {

            String res = null;
            JSONObject json = null;
            try {
                json = new JSONObject(str);
                res = json.getString("result");
                if("1".equals(res)){
                    intent.putExtra("result","success");
                } else if("0".equals(res)){
                    intent.putExtra("result","failure");
                }else {
                    intent.putExtra("result","failure");
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(res==null){
                intent.putExtra("result","failure");
            }
            mActivity.sendBroadcast(intent);
        }
    }

    private void CompleteUsrInfo(User user, JSONObject object) throws JSONException {
        String nickname = object.getString("username");
        int id = object.getInt("userid");
        int sex = object.getInt("sex");
        String detail = object.getString("udetail");
        String email = object.getString("email");
        String frog = object.getString("picture");
        int inte = object.getInt("inte");
        String realname = object.getString("realname");
        String stuNum = object.getString("stunum");
        String password = object.getString("password");

        user.setUsrId(id);
        if(!nickname.isEmpty()){
            user.setNickname(nickname);
            user.setSex(sex);
            user.setDetail(detail);
            user.setEmail(email);
            user.setFrog(frog);
            user.setInte(inte);
            user.setStdNum(stuNum);
            user.setRealname(realname);
        }else{
            user.setNickname(user.getPhoneNum());
        }
    }

    private Rewords getReword(JSONObject task) throws JSONException {
        Rewords r = new Rewords();
        r.setRewordId(task.getInt("bountyid"));
        r.setTaskTitle(task.getString("title"));
        r.setTaskType(task.getInt("type"));
        r.setTaskContent(task.getString("bdetail"));
        r.setPrice(task.getDouble("money"));
        r.setUsrId(task.getInt("auser"));
        r.setGeterId(task.getInt("buser"));
        Date date = new Date();
        JSONObject time = task.getJSONObject("deadtime");

        date.setTime(time.getInt("time"));
        Gson gson = new Gson();

        Log.i("okhttpRespondtime",date.toString());
        Log.i("okhttpRespondtime",time.toString());
        date.setMinutes(time.getInt("minutes"));
        date.setSeconds(time.getInt("seconds"));
        date.setHours(time.getInt("hours"));
        date.setMonth(time.getInt("month"));
        date.setYear(time.getInt("year"));
        date.setDate(time.getInt("date"));
        Log.i("okhttpRespondtime",date.toString());
//        date
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        r.setTaskDeadTime(format.format(date));
        return r;
    }

    private String TransToJasonLogin(User r) {
        String rs=null;
        rs = "{\"password\":\"" +r.getPassword()+"\","
                +"\"phone\":\"" +r.getPhoneNum()+"\"}";
        Log.i("okhttpRespond",rs);
        return  rs;

    }

    private String TransToJsonUpdate(User r){
        String rs=null;
        rs = "{\"userid\":\"" + r.getUsrId()+"\","
                +"\"Udetail\":\"" +r.getDetail()+"\","
                +"\"realname\":\"" +r.getRealname()+"\","
                +"\"stunum\":\"" +r.getStdNum()+"\","
                +"\"email\":\"" +r.getEmail()+"\","
                +"\"sex\":\"" +r.getSex()+"\"}";
        Log.i("okhttpRespond",rs);
        return  rs;
    }

    private String TransToJason(User r) {
        String rs=null;
        rs = "{\"username\":\"" + r.getNickname()+"\","
                +"\"password\":\"" +r.getPassword()+"\","
                +"\"phone\":\"" +r.getPhoneNum()+"\"}";
        Log.i("okhttpRespond",rs);
        return  rs;
    }

    private String TransToJason(Rewords r) {
        String rs=null;

        rs = "{\"title\":\"" + r.getTaskTitle()+"\","
                +"\"Bdetail\":\"" +r.getTaskContent()+"\","
                +"\"Auser\":\"" +r.getUsrId()+"\","
                +"\"money\":\"" +r.getPrice()+"\","
                +"\"type\":\"" +r.getTaskType()+"\","
                +"\"safe\":\"" +r.isBuyInsurance()+"\","
                +"\"deadTime\":\"" +r.getTaskDeadTime()+"\"}";
        Log.i("okhttpRespond",rs);
        return  rs;
    }

}
